package com.jiamao.goplay.ui.user.vm;

import android.app.Application;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.VerifiedInputEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.alibaba.fastjson.JSONObject;
import com.discussionavatarview.DensityUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.bean.AvatarList;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.res.ResImage;
import com.jiamao.goplay.bean.res.ResUserInfoDetail;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.AddrDetailFragment;
import com.jiamao.goplay.ui.login.vm.AddHeadImageModel;
import com.jiamao.goplay.ui.user.UpdateNameFragment;
import com.jiamao.goplay.ui.user.UserUpdateAhFragment;
import com.jiamao.goplay.util.GsonUtil;
import com.tamsiree.rxkit.view.RxToast;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class EditUserInfoNM extends BaseViewModel<DataRepository> {

    private ResUserInfoDetail detail;
    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>("");
    public ObservableField<String> sex = new ObservableField<>("");
    //出生年月日
    public ObservableField<String> birthday = new ObservableField<>("");
    //对应星座
    public ObservableField<String> gotoNumDec = new ObservableField<>("我想去的(0)");
    public ObservableField<String> phoneNumDec = new ObservableField<>("0张");
    public ObservableField<String> age = new ObservableField<>("");
    public ObservableField<String> sz = new ObservableField<>("");
    public ObservableField<String> sg = new ObservableField<>("");
    public ObservableField<String> tz = new ObservableField<>("");
    public ObservableField<String> hy = new ObservableField<>("");
    public ObservableField<String> zw = new ObservableField<>("");
    public ObservableField<String> dx = new ObservableField<>("");
    public ObservableField<String> ah = new ObservableField<>("");
    public ObservableField<String> des = new ObservableField<>("");
    public ObservableField<String> id = new ObservableField<>("");
    public ObservableField<String> gs = new ObservableField<>("");


    public int isTouXiangRenzh = 0 ;

    public int index;


    public EditUserInfoNM(@NonNull Application application, DataRepository model) {
        super(application, model);



        Messenger.getDefault().register(this, Config.MGER_PHOTO_EDIT,  String.class, new BindingConsumer<String>() {
            @Override
            public void call(String path) {


               // uc.image.setValue(path);


                observableListImage.remove(index);

                com.jiamao.goplay.bean.AvatarList avatarList = new com.jiamao.goplay.bean.AvatarList();
                avatarList.setUrl(path);
                avatarList.setIsDefault(-1);
                avatarList.setType(index==0?0:1);
                avatarList.setAuth(1);
                MultiItemViewModel itemPhone= new EditUserPhotoItemVM(EditUserInfoNM.this,avatarList);
                itemPhone.multiItemType("image");
                observableListImage.add(index,itemPhone);
                //  uc.pSwitchEvent.setValue("");
            }
        });


        Messenger.getDefault().register(this, Config.MGER_USER_EDIT_NAME, Bundle.class, new BindingConsumer<Bundle>() {
            @Override
            public void call(Bundle aMapLocation) {
                Log.d("HTML","aMapLocation");
                switch (aMapLocation.getInt("type")){
                    case 1:
                        userName.set(aMapLocation.getString("name"));
                        break;
                    case 2:
                        des.set(aMapLocation.getString("name"));
                        break;
                    case 3:
                        dx.set(aMapLocation.getString("name"));
                        break;
                    case 4:
                        gs.set(aMapLocation.getString("name"));
                        break;
                }

            }


        });

        Messenger.getDefault().register(this, Config.MGER_USER_EDIT_AH, String.class, new BindingConsumer<String>() {
            @Override
            public void call(String aMapLocation) {
                Log.d("HTML","aMapLocation");
                        ah.set(aMapLocation);

            }


        });

        Messenger.getDefault().register(this, "123", String.class, new BindingConsumer<String>() {
            @Override
            public void call(String aMapLocation) {
                Log.d("HTML","AAAAAAAAAAAAAASSSS");

            }

        });


    }

    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Integer> showPhoto = new SingleLiveEvent<>();
        public SingleLiveEvent<String> image = new SingleLiveEvent<>();

        //密码开关观察者
        public SingleLiveEvent<Boolean> showTime = new SingleLiveEvent<>();

        public SingleLiveEvent<Integer> showSex = new SingleLiveEvent<>();


        public SingleLiveEvent<EditUserPhotoItemVM> showUploadImg = new SingleLiveEvent<>();

    }


    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableListImage = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBindingImage = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();
            if (itemType.equals("add")){
                itemBinding.set(BR.viewModel, R.layout.user_edit_photo_item_add_layout);
            }else {

                itemBinding.set(BR.viewModel, R.layout.user_edit_photo_item_layout);
            }
            //设置头布局


        }
    });


    public void initLoadData(ResUserInfoDetail info){

        detail = info;

        if (info.getBaseInfo()!=null){
            userName.set( info.getBaseInfo().getNickname());
            id.set(info.getBaseInfo().getId()+"");
            sex.set(info.getBaseInfo().getGender()==1?"男":"女");
            isTouXiangRenzh =  info.getCertification().getAvatarVerified();

        }
        if (info.getUserInfo()!=null){
            birthday.set(info.getUserInfo().getBirthday());
            age.set(info.getUserInfo().getAge()+"");
            sz.set(info.getUserInfo().getGalaxy());
            sg.set(info.getUserInfo().getHeight());
            tz.set(info.getUserInfo().getWeight());
            hy.set(info.getUserInfo().getIndustry());
            zw.set(info.getUserInfo().getPosition());
            dx.set(info.getUserInfo().getUniversity());
            ah.set(info.getUserInfo().getInterest());
            if(!TextUtils.isEmpty(info.getUserInfo().getDescribe())){
                des.set(info.getUserInfo().getDescribe());
            }

            gs.set(info.getUserInfo().getCompany());

        }


        if (info.getPlaceWantGo() != null){
            gotoNumDec.set("我想要的("+info.getPlaceWantGo().size()+")");
        }



        if (info.getAvatarList()!=null){
            phoneNumDec.set(info.getAvatarList().size()+"张");
            observableListImage.clear();

            ArrayList<String> imgList = new ArrayList<>();
            for (int i=0;i<info.getAvatarList().size();i++){
                imgList.add(info.getAvatarList().get(i).getUrl());
            }

            for (int i=0;i<info.getAvatarList().size();i++){
                MultiItemViewModel itemPhone= new EditUserPhotoItemVM(this,info.getAvatarList().get(i));
                itemPhone.multiItemType("image");
                observableListImage.add(itemPhone) ;

            }

            for (int i=0;i<6-info.getAvatarList().size();i++){
                MultiItemViewModel item2 = new UserEditPhotoAddrItemVM(this,i);
                //条目类型为右布局
                item2.multiItemType("add");
                observableListImage.add(item2);

            }
        }




    }


//    public void uploadImage(String path,int index){
//        int type = 0 ;
//        if (index == 0 ){
//            type = 1;
//        }
//        File file = new File(path);
//        //上传图片需要MultipartBody
//        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
//
//        MultipartBody.Part body = MultipartBody.Part.createFormData("File", file.getName(), requestBody);
//
//
//        RequestBody param = RequestBody.create(MediaType.parse("text/plain"), type+"");
//
//
//        model.getApi().uploadImage(body,param)
//                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
//                .compose(RxUtils.schedulersTransformer())  // 线程调度
//                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
//                .doOnSubscribe(this) //请求与ViewModel周期同步
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Exception {
//                        showDialog();
//                        // dialog.show();
//                    }
//                })
//                .subscribe(new DisposableObserver<BaseRep<ResImage>>() {
//
//                    @Override
//                    public void onError(Throwable throwable) {
//                        //关闭对话框
//                        dismissDialog();
//                        //请求刷新完成收回
//                        RxToast.showToastShort(throwable.getMessage());
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        dismissDialog();
//                    }
//
//                    @Override
//                    public void onNext(BaseRep<ResImage> o)   {
//                        dismissDialog();
//                        if (o.isOk()){
//
//                           observableListImage.remove(index);
//
//                            com.jiamao.goplay.bean.AvatarList avatarList = new com.jiamao.goplay.bean.AvatarList();
//                            avatarList.setUrl(o.getData().getPath());
//                            avatarList.setIsDefault(-1);
//                            avatarList.setType(index==0?1:0);
//                            avatarList.setAuth(1);
//                            MultiItemViewModel itemPhone= new EditUserPhotoItemVM(EditUserInfoNM.this,avatarList);
//                            itemPhone.multiItemType("image");
//                           observableListImage.add(index,itemPhone);
//                            //uc.image.setValue(o.getData().getPath());
//
//                        }else {
//                            RxToast.showToastShort(o.getMsg());
//                        }
//                    }
//                });
//
//
//
//    }







    //条目的点击事件
    public BindingCommand updateNameCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            Bundle bd  =new Bundle();
            bd.putInt("type",1);
            bd.putString("name",userName.get());
            startContainerActivity(UpdateNameFragment.class.getCanonicalName(),bd);
        }
    });

    //条目的点击事件
    public BindingCommand updateGongshiCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            Bundle bd  =new Bundle();
            bd.putInt("type",4);
            bd.putString("name",gs.get());
            startContainerActivity(UpdateNameFragment.class.getCanonicalName(),bd);
        }
    });

    //条目的点击事件
    public BindingCommand updateAboutCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            Bundle bd  =new Bundle();
            bd.putInt("type",2);
            bd.putString("name",des.get());
            startContainerActivity(UpdateNameFragment.class.getCanonicalName(),bd);
        }
    });

    //条目的点击事件
    public BindingCommand updateShcolCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            Bundle bd  =new Bundle();
            bd.putInt("type",3);
            bd.putString("name",dx.get());
            startContainerActivity(UpdateNameFragment.class.getCanonicalName(),bd);
        }
    });

    //条目的点击事件
    public BindingCommand updateAgeCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

                uc.showTime.setValue(true);
        }
    });

    //条目的点击事件
    public BindingCommand updateSexCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

        //    uc.showSex.setValue(1);
        }
    });


    //条目的点击事件
    public BindingCommand updateShenGaoCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            uc.showSex.setValue(2);
        }
    });

    //条目的点击事件
    public BindingCommand updateAhCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bd =new Bundle();
            bd.putString("ah",ah.get());
            startContainerActivity(UserUpdateAhFragment.class.getCanonicalName(),bd);
          //  uc.showSex.setValue(2);
        }
    });

    //条目的点击事件
    public BindingCommand updateTizhongCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            uc.showSex.setValue(3);
        }
    });

    //条目的点击事件
    public BindingCommand updatehyCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            uc.showSex.setValue(4);
        }
    });

    //条目的点击事件
    public BindingCommand updatelyCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            uc.showSex.setValue(5);
        }
    });

    //检测是否修改了数据
    public boolean checkIsEditData(){

        if ( !detail.getBaseInfo().getNickname().equals(userName.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getGalaxy().equals(sz.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getHeight().equals(sg.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getWeight().equals(tz.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getIndustry().equals(hy.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getPosition().equals(zw.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getUniversity().equals(dx.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getInterest().equals(ah.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getDescribe().equals(des.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getCompany().equals(gs.get())){     KLog.d("aaaaaa");
            return true;
        }
        if ( !detail.getUserInfo().getBirthday().equals(birthday.get())){
            KLog.d("aaaaaa");
            return true;
        }

        ArrayList<AvatarList>  arrayList = detail.getAvatarList();
//        if (arrayList.size() != observableListImage.size()-1 ){     KLog.d("aaaaaa");
//            return true;
//        }




        for (int i=0;i<observableListImage.size();i++){



            if(observableListImage.get(i).getItemType().equals("image")){
                String url =((EditUserPhotoItemVM)observableListImage.get(i)).imgUrl.get();
                if (i >= arrayList.size()){
                    return true;
                }
                if (!url.equals(arrayList.get(i).getUrl())){
                    KLog.d("aaaaaa");
                    return true;
                }
            }
        }

        return false;
    }

    public void submit(){

        detail.getBaseInfo().setNickname(userName.get());

        detail.getUserInfo().setGalaxy(sz.get());
        detail.getUserInfo().setHeight(sg.get());
        detail.getUserInfo().setWeight(tz.get());
        detail.getUserInfo().setIndustry(hy.get());
        detail.getUserInfo().setPosition(zw.get());
        detail.getUserInfo().setUniversity(dx.get());
        detail.getUserInfo().setInterest(ah.get());
        detail.getUserInfo().setDescribe(des.get());
        detail.getUserInfo().setCompany(gs.get());
        detail.getUserInfo().setBirthday(birthday.get());

        ArrayList<AvatarList>  arrayList = detail.getAvatarList();
        arrayList.clear();
        for (int i=0;i<observableListImage.size();i++){

           if(observableListImage.get(i) instanceof EditUserPhotoItemVM){

           }
            if(observableListImage.get(i).getItemType().equals("image")){
                AvatarList avatarList = new AvatarList();
                avatarList.setId(i+0);
                if (i == 0){
                    avatarList.setType(0);
                }else{
                    avatarList.setType(1);
                }

                avatarList.setAuth(1);
                avatarList.setIsDefault(0);
                avatarList.setUrl(((EditUserPhotoItemVM)observableListImage.get(i)).imgUrl.get());
                arrayList.add(avatarList);
            }
        }
      //  JSONObject jsonObject = new JSONObject();


      //  JsonObject daas = (JsonObject) new JsonParser().parse(GsonUtil.toJson(detail));

      //  jsonObject.put("content", JSONObject.parse(GsonUtil.toJson(detail)));
          String json =   GsonUtil.toJson(detail);
        Log.d("HTML",json);
            postData(json);
    }


    public void postData(String json){

       // String body = "{\"token\": \"This is a token!\"}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
        model.getApi().editUserInfo(requestBody)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                            showDialog();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResUserInfoDetail>>() {
                    @Override
                    public void onNext(BaseRep<ResUserInfoDetail> baseRep) {
                        super.onNext(baseRep);
                          dismissDialog();
                        // dialog.dismiss();
                        //保存账号密码
                        if (baseRep.isOk()){
                            model.getmLocalDataSource().saveUserInfo(GsonUtil.toJson(baseRep.getData()));
                            finish();

                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {

                    }

                });
    }
    public void showUpateImage(EditUserPhotoItemVM avatarList){

         uc.showUploadImg.setValue(avatarList);

    }
}
